import cv2
import os
import PIL.Image
import time

def DetectFaces(image_name):
    img = cv2.imread(image_name)
    face_cascade = cv2.CascadeClassifier("F:/my_package/opencv/sources/data/haarcascades/haarcascade_frontalface_alt_tree.xml")
    if img.ndim == 3:
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    else:
        gray = img 

    faces = face_cascade.detectMultiScale(gray, 1.2, 5)
    result = []
    for (x,y,width,height) in faces:
        result.append((x,y,x+width,y+height))
    return result

def SaveFaces(image_name,faces,save_dir):
    # faces = DetectFaces(image_name)
    if faces:
        # save_dir = image_name.split('.')[0]+"_faces"
        # save_dir=os.path.split(image_name)[1].split('.')[0]+"_boomfaces"
        os.mkdir(save_dir)
        count = 0
        for (x1,y1,x2,y2) in faces:
            # print count,'th part begin...'
            t1=time.time()
            file_name = os.path.join(save_dir,str(count)+".jpg")
            PIL.Image.open(image_name).crop((x1,y1,x2,y2)).save(file_name)
            count+=1
            t2=time.time()
            t=t2-t1
            # print count,'th part end... take time:',t

# img_dir='F:/face-recognition/age_gender/'
# img_name='xdd4.jpg'
# img_file=img_dir+img_name
# r=detectFaces(img_file)
# print r
# saveFaces(img_file)